package com.yunfinal.api.service.plugin;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.kit.Prop;
import com.jfinal.plugin.IPlugin;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.yunfinal.api.service.JFinalApiConfig;

/**
 * 方便后续可扩展
 */
public class DbConfigPlugin implements IPlugin {

    protected WallFilter wallFilter;
    protected DruidPlugin dp = newDruidPlugin();
    protected ActiveRecordPlugin arp = newActiveRecordPlugin(dp);

    public ActiveRecordPlugin newActiveRecordPlugin(DruidPlugin dp) {
        Prop p = JFinalApiConfig.getProp();
        ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);
        //arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED);
        arp.setShowSql(p.getBoolean("devMode", false));
        arp.addSqlTemplate("/sql/common.sql");
        //注册 表映射
        addMapping(arp);
        return arp;
    }

    protected void addMapping(ActiveRecordPlugin arp) {
//        arp.addMapping("tableName", Model.class);
    }

    public DruidPlugin newDruidPlugin() {
        Prop p = JFinalApiConfig.getProp();
        DruidPlugin druidPlugin = new DruidPlugin(
                p.get("mysql.jdbcUrl"), p.get("mysql.userName"), p.get("mysql.passWord"));
        // 加强数据库安全
        wallFilter = new WallFilter();
        wallFilter.setDbType("mysql");
        druidPlugin.addFilter(wallFilter);
        // 添加 StatFilter 才会有统计数据
        druidPlugin.addFilter(new StatFilter());
        return druidPlugin;
    }

    @Override
    public boolean start() {
        dp.start();
        arp.start();
        wallFilter.getConfig().setSelectUnionCheck(false);
        return true;
    }

    @Override
    public boolean stop() {
        dp.stop();
        arp.stop();
        return true;
    }

    public static DruidStatViewHandler getDruidStatViewHandler() {
        Prop p = JFinalApiConfig.getProp();
        String url = p.get("DruidStatViewAuthUrl", "/assets/druid");
        return new DruidStatViewHandler(url);
    }
}
